/**
 * Alipay.com Inc. Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.study.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

/**
 * @author wb-whl357206
 * @version $Id: ClassUtil.java, v 0.1 2018年07月06日 14:32 wb-whl357206 Exp $
 */
public class ClassUtil {

    private static final Log logger = LogFactory.getLog(ClassUtil.class);

    public static final String JAVA_FILE_ENDING = "java";

    public static final String CLASS_FILE_ENDING = "class";

    public static final String NAME_CONNECTOR = ".";

    private boolean error_log = false;

    private JavaCompiler compiler;

    public String classPath;

    public String srcPath;

    public String rootPath;

    public ClassUtil(String rootPath, String classPath, String srcPath) {
        this.rootPath = rootPath;
        this.classPath = classPath;
        this.srcPath = srcPath;
        compiler = ToolProvider.getSystemJavaCompiler();
    }


    public void doJavac(String path) {
        //List<String> ops = Arrays.asList("-encoding", "UTF-8", "-classpath", jars, "-d", targetDir, "-sourcepath", sourceDir);
        List<String> ops = Arrays.asList("-encoding", "UTF-8", "-d", rootPath + "/" + classPath);
        javac(ops, path);
    }

    /**
     * 加载类
     *
     * @param name 类名
     * @return
     */
    public Class<?> load(String name) {
        Class<?> cls = null;
        ClassLoader classLoader = null;
        try {
            classLoader = FileUtil.class.getClassLoader();
            cls = classLoader.loadClass(name);
            if (logger.isDebugEnabled()) {
                logger.debug("Load Class[" + name + "] by " + classLoader);
            }
        } catch (Exception e) {
            if (error_log) {
                logger.error(e);
            }
        }
        return cls;
    }

    /**
     * 编译java文件
     *
     * @param ops  编译参数
     * @param file 编译文件
     */
    public void javac(List<String> ops, String file) {
        StandardJavaFileManager manager = null;
        try {
            manager = compiler.getStandardFileManager(null, null, null);
            Iterable<? extends JavaFileObject> it = manager.getJavaFileObjects(file);
            String path = file.replace(srcPath, classPath).replace(".java", ".class");
            System.out.println(path);
            Writer out = new FileWriter(path);
            JavaCompiler.CompilationTask task = compiler.getTask(out, manager, null, ops, null, it);
            task.call();
        } catch (Exception e) {
            logger.error(e);
        } finally {
            if (manager != null) {
                try {
                    manager.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取路径
     *
     * @param packagePath 包名
     * @param outFile     文件名
     * @return
     */
    public String getPath(String packagePath, String outFile) {
        return StringUtil.build(rootPath, "/", srcPath, "/", packagePath.replaceAll("\\.", "/"), "/", outFile);
    }

    /**
     * 获取java文件名
     *
     * @param fileName 文件名
     * @return
     */
    public String getJavaFileName(String fileName) {
        return StringUtil.build(fileName, NAME_CONNECTOR, JAVA_FILE_ENDING);
    }

    /**
     * 获取枚举类全限定名
     *
     * @param packageInfo 包名
     * @param className   类名
     * @return
     */
    public String getEnumClassName(String packageInfo, String className) {
        return StringUtil.build(packageInfo, ClassUtil.NAME_CONNECTOR, className.substring(0, 1).toUpperCase(), className.substring(1));
    }
}